package com.ddm.controller.web;

import cn.hutool.db.PageResult;
import com.ddm.result.Result;
import com.ddm.service.webService.UserSubscribeService;
import com.ddm.vo.webVo.SubscribeDetailVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 用户订阅控制器
 */
@Slf4j
@RestController
@RequestMapping("/user/subscribe")
public class UserSubscribeController {

    @Resource
    private UserSubscribeService userSubscribeService;

    /**
     * 查询用户的订阅详情
     */
    @GetMapping("/userDetail")
    public Result<List<SubscribeDetailVO>> getUserSubscribeDetail(@RequestParam Long userId) {
        List<SubscribeDetailVO> data = userSubscribeService.getUserSubscribeDetail(userId);
        return Result.success(data);
    }

    /**
     * 查询用户的订阅详情
     */
    @GetMapping("/getSubIdByUserAndPlanId")
    public Result<Map> getUserSubscribeDetail(@RequestParam Integer userId, @RequestParam Integer planId) {
        Long subId=userSubscribeService.getSubIdByUserAndSubscription(userId,planId);
        Map<String, Object> data = new HashMap<>();
        data.put("subId", subId);
        return Result.success(data);
    }

    /**
     * 查询即将到期的订阅
     */
    @GetMapping("/expiring")
    public Result<List<SubscribeDetailVO>> getExpiringSubscribes(Integer days) {
        List<SubscribeDetailVO> data = userSubscribeService.getExpiringSubscribes(days);
        return Result.success(data);
    }


    /**
     * 查询订阅到期提醒记录
     * 支持多条件组合查询
     */
    @GetMapping("/listExpiringSubscribesByParams")
    @ApiOperation(value = "查询订阅到期提醒记录", notes = "可根据用户ID、套餐ID、到期日期范围等条件查询")
    public Result<List<SubscribeDetailVO>> getExpiringSubscribes(
            @ApiParam(value = "用户ID") @RequestParam(required = false) Long userId,
            @ApiParam(value = "套餐ID") @RequestParam(required = false) Long planId,
            @ApiParam(value = "到期日期起始（包含）") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startEndDate,
            @ApiParam(value = "到期日期结束（包含）") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endEndDate,
            @ApiParam(value = "自动续费状态（0-不自动续费，1-自动续费）") @RequestParam(required = false) Integer autoRenew,
            @ApiParam(value = "创建时间起始（包含）") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startCreateTime,
            @ApiParam(value = "创建时间结束（包含）") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endCreateTime) {

        // 构建查询参数
        Map<String, Object> params = new TreeMap<>();
        params.put("userId", userId);
        params.put("planId", planId);
        params.put("startEndDate", startEndDate);
        params.put("endEndDate", endEndDate);
        params.put("autoRenew", autoRenew);
        params.put("startCreateTime", startCreateTime);
        params.put("endCreateTime", endCreateTime);
        // 调用服务层查询
        List<SubscribeDetailVO> result = userSubscribeService.selectExpiringSubscribesByParams(params);
        return Result.success(result);
    }

    /**
     * 检查用户是否有有效订阅
     */
    @GetMapping("/hasValid")
    public Result<Map> hasValidSubscribe(@RequestParam Long userId) {
        Map hasValid = userSubscribeService.hasValidSubscribe(userId);
        return Result.success(hasValid);
    }

    /**
     * 检查用户是否有有效订阅
     */
    @PostMapping("/add")
    public Result<String> addSubscribe(
            // 前端必传：用户ID
            @RequestParam @NotNull(message = "用户ID不能为空") Long userId,
            // 前端必传：套餐ID
            @RequestParam @NotNull(message = "套餐ID不能为空") Long planId
    ){
        try {
            // 调用Service，直接传递两个参数
            boolean success = userSubscribeService.addSubscribe(userId, planId);
            return success ? Result.success("订阅添加成功") : Result.error("订阅添加失败");
        } catch (IllegalArgumentException e) {
            // 业务异常（如用户/套餐不存在、重复订阅）
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("添加订阅失败，userId: {}, planId: {}", userId, planId, e);
            return Result.error("添加订阅失败：" + e.getMessage());
        }
    }

    /**
     * 修改订阅状态和自动续费情况（不依赖影响行数判断）
     */
    @PostMapping("/updateStatus")
    public Result<String> updateSubscribeStatus(
            @RequestParam @NotNull(message = "订阅记录ID不能为空") Long subId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer autoRenew) {

        // 参数验证逻辑不变
        if (status != null && (status < 0 || status > 2)) {
            return Result.error("订单状态无效，必须是0（待支付）、1（已支付）或2（退款）");
        }
        if (autoRenew != null && (autoRenew < 0 || autoRenew > 1)) {
            return Result.error("自动订阅状态无效，必须是0（不自动）或1（自动）");
        }
        if (status == null && autoRenew == null) {
            return Result.error("至少需要修改一个参数（状态或自动订阅）");
        }

        try {
            boolean success = userSubscribeService.updateSubscribeStatus(subId, status, autoRenew);
            return success ? Result.success("订阅信息更新成功") : Result.error("订阅记录不存在或未发生变更");
        } catch (Exception e) {
            log.error("修改订阅状态失败，subId: {}, status: {}, autoRenew: {}", subId, status, autoRenew, e);
            return Result.error("修改订阅状态失败：" + e.getMessage());
        }
    }

    /**
     * 查询订阅记录列表（支持分页和条件筛选）
     *
     * @param userId 可选，用户ID，用于筛选特定用户的订阅
     * @param status 可选，订单状态（0待支付 1已支付 2退款）
     * @param autoRenew 可选，自动订阅情况（0不自动 1自动）
     * @param page 页码，默认1
     * @param pageSize 每页条数，默认10
     * @return 分页后的订阅记录列表
     */
    @GetMapping("/list")
    public Result<PageResult<SubscribeDetailVO>> getSubscribeList(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer autoRenew,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 验证参数有效性
        if (status != null && (status < 0 || status > 2)) {
            return Result.error("订单状态无效，必须是0（待支付）、1（已支付）或2（退款）");
        }
        if (autoRenew != null && (autoRenew < 0 || autoRenew > 1)) {
            return Result.error("自动订阅状态无效，必须是0（不自动）或1（自动）");
        }

        PageResult<SubscribeDetailVO> result = userSubscribeService.getSubscribeList(
                userId, status, autoRenew, page, pageSize);
        return Result.success(result);
    }

}